| Total Complexity | 4 |
| Total Lines | 48 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | import I18n from '@ioc:Adonis/Addons/I18n' |
||
| 3 | |||
| 4 | /** |
||
| 5 | * The middleware detects the user language using the "Accept-language" HTTP header |
||
| 6 | * or the "lang" query string parameter. |
||
| 7 | * |
||
| 8 | * Feel free to change the middleware implementation to what suits your needs. Just |
||
| 9 | * make sure |
||
| 10 | * |
||
| 11 | * - You always ensure the user selected language is supported by your app. |
||
| 12 | * - Only call "switchLocale" when the detected language is valid string value and |
||
| 13 | * not "null" or "undefined" |
||
| 14 | */ |
||
| 15 | export default class DetectUserLocale { |
||
| 16 | /** |
||
| 17 | * Detect user language using "Accept-language" header or |
||
| 18 | * the "lang" query string parameter. |
||
| 19 | * |
||
| 20 | * The user language must be part of the "supportedLocales", otherwise |
||
| 21 | * this method should return null. |
||
| 22 | */ |
||
| 23 | protected getUserLanguage(ctx: HttpContextContract) { |
||
| 24 | const availableLocales = I18n.supportedLocales() |
||
| 25 | return ctx.request.language(availableLocales) || ctx.request.input('lang') |
||
| 26 | } |
||
| 27 | |||
| 28 | /** |
||
| 29 | * Handle method is called by AdonisJS automatically on every middleware |
||
| 30 | * class. |
||
| 31 | */ |
||
| 32 | public async handle(ctx: HttpContextContract, next: () => Promise<void>) { |
||
| 33 | const language = this.getUserLanguage(ctx) |
||
| 34 | |||
| 35 | /** |
||
| 36 | * Switch locale when we are able to detect the user language and it |
||
| 37 | * is supported by the application |
||
| 38 | */ |
||
| 39 | if (language) { |
||
| 40 | ctx.i18n.switchLocale(language) |
||
| 41 | } |
||
| 42 | |||
| 43 | /** |
||
| 44 | * Share i18n with view |
||
| 45 | */ |
||
| 46 | if ('view' in ctx) { |
||
| 47 | ctx.view.share({ i18n: ctx.i18n }) |
||
| 48 | } |
||
| 49 | |||
| 50 | await next() |
||
| 51 | } |
||
| 53 |